<?php
	/* The private calendar */
	class CalendarCompanyController extends Zone_Action{
		public function fields( $default=NULL ){
			$data = array(
				updated_by_id	=> array(
					type			=> 'NONE',
					default_value	=> get_user_id()
				),
				department_id	=> array(
					type			=> 'INT',
					default_value	=> 0
				),
				date_updated => array(
					type			=> 'NONE',
					default_value	=> new Model_Expr('NOW()')
				),
				type	=> array(
					type			=> 'NONE',
					default_value	=> 'company'
				),				
				title => array(
					type => 'CHAR',
					no_empty => true,
					form_label => 'Tiêu đề'
				),				
				place => array(
					type => 'CHAR',
					form_label => 'Địa điểm'
				),				
				tools => array(
					type => 'CHAR',
					form_label => 'Chuẩn bị'
				),				
				guests => array(
					type => 'CHAR',
					form_label => 'Thành phần tham gia'
				),				
				chairman => array(
					type 		=> 'CHAR',
					form_label 	=> 'Chủ trì'
				),
				content => array(
					type 		  => 'HTML',
					form_label 	  => 'Mô tả',
					default_value => ''
				),
				date_start	=> array(
					type		=> 'DATE',
					no_empty	=> true,
					form_label  => 'Ngày bắt đầu',
					fix_value	=> change_date_format
				),
				time_start	=> array(
					type		=> 'CHAR',
					no_empty	=> true,
					form_label 	=> 'Giờ bắt đầu'				
				),
				time_end	=> array(
					type			=> 'CHAR',
					form_label  	=> 'Giờ kết thúc',
					default_value	=> NULL	
				),
				repeat_type	=> array(
					type		=> 'ENUM',
					value		=> array('none','day','week','month','year'),
					form_label  => 'Kiểu lặp'				
				),
				repeat_day	=> array(
					type		=> 'LIST',
					form_label  => 'Thứ lặp',
					comma		=>	',',
					value		=> array('0','1','2','3','4','5','6')
				),
				repeat_date_end	=> array(
					type	=> 'DATE',
					form_label 		=> 'Ngày kết thúc lặp',
					fix_value		=> change_date_format,
					default_value	=>	NULL
				),
				repeat_time_number	=> array(
					type		=> 'ENUM',
					value		=>	array('0','1','2','5','10','30'),
					form_label  => 'Thời gian lặp'				
				),
				repeat_time_unit	=> array(
					type		=> 'ENUM',
					value		=>	array('1','60','1440','10080'),
					form_label 	=> 'Đơn vị lặp'				
				),
				repeat_email	=> array(
					type 	  		=> 'CHAR',
					default_value 	=> 'no',
					form_label 		=> 'Nhắc bằng email'				
				),
				repeat_alert   => array(
					type	 		  	=> 'CHAR',
					default_value 		=> 'no',
					form_label 			=> 'Nhắc bằng thông báo'				
				),
				is_approve	=> array(
					type			=> 'NONE',
					default_value	=> 'yes'
				)	
			);
			
			if( is_array( $default ) ){
				foreach( $data as $k => $config ){
					if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
						$data[$k]['default_value'] = $default[$k];
					}
				}
			}	
			return $data;	
		}	

		public function initAction(){
			if(!$this->hasRole('calendar')){
				$this->removeLayout();
				$this->setContent(error('Bạn không được phép truy cập phân hệ này.'));	
				$this->stop();
			}
			
			$departments = $this	
				->Model
				->fetchAll("SELECT `a`.* 
					FROM `departments` as `a` 
					LEFT JOIN `departments` as `b`
						ON `a`.`parent_id`=`b`.`ID`
					LEFT JOIN `departments` as `c`
						ON `b`.`parent_id`=`c`.`ID`
					WHERE 
						`b`.`ID` IS NOT NULL AND `c`.`ID` IS NULL");
			
			$this->set('departments',$departments);
		}		
		
		private function getOptions(){
			$departs = $this	
				->Model
				->fetchAll("SELECT `a`.* 
					FROM `departments` as `a` 
					LEFT JOIN `departments` as `b`
						ON `a`.`parent_id`=`b`.`ID`
					LEFT JOIN `departments` as `c`
						ON `b`.`parent_id`=`c`.`ID`
					WHERE 
						`c`.`ID` IS NULL");		
			$this->set('departs', $departs);						
		}		
		
		protected function getCalendar( $time, $date ){
			$user_id = get_user_id();
			$expr = getInt('department_id',0) != 0	
				? (' AND `a`.`department_id`="'.getInt('department_id').'"') : '';
				
			return $this->Model->fetchAll("SELECT `a`.*,`b`.`title` as `department_title`
				FROM `calendars` as `a`
				LEFT JOIN `departments` as `b`
					ON `a`.`department_id`=`b`.`ID`
				WHERE 
					`a`.`is_draft`='no'
					$expr
					AND `a`.`type`='company'
				AND `a`.`date_start` <= '$date'	
				AND (
					( `a`.`repeat_type`='none' AND `a`.`date_start`='$date'  )
					OR (
						( `a`.`repeat_date_end` IS NULL OR `a`.`repeat_date_end` >= '$date' )
						AND(
							( `a`.`repeat_type`='day' AND CONCAT(',',`a`.`repeat_day`,',') LIKE '%,".(date('N',$time)%7).",%' ) 
							OR ( `a`.`repeat_type`='week'  AND DAYOFWEEK(`a`.`date_start`)  = '".(date('N',$time)%7)."'  ) 
							OR ( `a`.`repeat_type`='month' AND DAYOFMONTH(`a`.`date_start`) = DAYOFMONTH('$date')  )
							OR ( `a`.`repeat_type`='year'  AND DAYOFMONTH(`a`.`date_start`) = DAYOFMONTH('$date') AND MONTH(`a`.`date_start`) = MONTH('$date') ) 
						)
					)		
				)	
				ORDER BY `a`.`time_start`");		
		}
				
		public function indexAction(){
			$date = get('date',date('Y-m-d'));
			$time = strtotime($date);
			$year = (int)get('year',$time);
			$week = (int)get('week',$time);
			
			$posts = $this->getCalendar($time,$date);
			$this->set(array(
				posts	=> $posts,
				time	=> $time
			));			
		
		}		
		
		public function listAction(){
			$user_id = get_user_id();
			$vars = array();
			$where = array();
			$order_by = "ORDER BY `a`.`ID` DESC";
			
			$current_page = max(getInt('p',1),1);		
			$range_page = max(10,(int)$this->getConfig('user.page',20));
			
			if( isset($_REQUEST['p']) ){
				$vars['p'] = $current_page;
			}
			
			$where[] ="`a`.`is_draft`='no'";
			$where[] ="`a`.`type`='company'";
			
			if( isset($_REQUEST['department_id']) ){
				$vars['department_id'] = get('department_id');
				$where[]="`a`.`department_id`='{$vars['department_id']}'";
			}
			
			$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
					
			$field_order = array('title','created_by_id','department_id','place','tools');
			foreach( $field_order as $f ){
				if( get('order_by') == $f ){
					$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
					$vars['order_by'] = $f;
					if( get('order_type') == 'desc' ){
						$vars['order_by']='desc';
					}
					break;	
				}	
			}		
			
			$total = $this->Model->fetchOne("SELECT COUNT(*) 
					FROM `calendars` as `a`
					WHERE ".implode(' AND ',$where));
					
			$posts = $this->Model->fetchAll("SELECT `a`.*
					,`b`.`title` as `department_title`
					,`c`.`username` as `created_by_name`
					,`c`.`is_deleted` as `created_is_deleted`
				FROM `calendars` as `a`
				LEFT JOIN `departments` as `b`
					ON `a`.`department_id`=`b`.`ID`
				LEFT JOIN `users` as `c`
					ON `a`.`created_by_id`=`c`.`ID`
				WHERE ".implode(' AND ',$where)."
			$order_by $limit");
					
			$a = $vars;
			unset($a['p']);
			
			$page = page_ajax('#Calendar/Company/List?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
				
			$this->set(array(
				page	=> $page,
				total	=> $total,
				vars	=> $vars,
				posts	=> $posts
			));		
		}				
		
		public function weekAction(){			
			$year = (int)get('year',date("Y",time()));
			$week = (int)get('week',(int)date("W",time()));
			$time = strtotime("{$year}W{$week}1");
			
			$days = array();
			
			for( $i=1; $i <= 7; $i++ ){
				$ctime = strtotime("{$year}W{$week}{$i}");
				$cdate = date('Y-m-d', $ctime );
				
				$calendars = $this->getCalendar($ctime,$cdate);				
				$days[ $ctime ] = $calendars;				
			}
		
			$this->set(array(
				days	=> $days,
				time	=> $time
			));
		}

		public function monthAction(){			
			$year = (int)get('year',date("Y",time()));
			$month = (int)get('month',(int)date("m",time()));
			$time = strtotime("$year-$month-01");
			$months = array();
			
			for( $i=1; $i <= 31; $i++ ){
				$ktime = mktime(0,0,0,$month,$i,$year);
				if( (int)date('m',$ktime) != $month ){
					break;
				}
				$date = date("Y-m-d",$ktime);
				$y = (int)date("Y",$ktime);
				$m = (int)date("m",$ktime);
				$d = (int)date("d",$ktime);
				
				
				$calendars = $this->getCalendar($ktime,$date);				
				$months["$y-$m-$d"] = $calendars;				
			}
		
			$this->set(array(
				months	=> $months,
				year	=> $year,
				month	=> $month,
				time	=> $time
			));
		}		
		
		protected function checkData( $data, $form ){
			if( !is_array( $data ) ){
				return $data;
			}
			
			if( $data['time_start']  && $data['time_end'] && ( strtotime($data['time_end']) <= strtotime($data['time_start']) ) ){
				return "Thời gian kết thúc phải lớn hơn thời gian bắt đầu.";
				$form->freeFile();
			}

			if( $data['date_start']  && $data['repeat_date_end'] && ( strtotime($data['date_start']) > strtotime($data['repeat_date_end']))
			){
				return "Thời gian kết thúc lặp không nhỏ hơn thời gian bắt đầu.";
				$form->freeFile();
			}
			
			return $data;
		}		
	
		public function addAction(){
			if( !$this->hasRole('add_company_calendar') ){
				return $this->setContent(error('Bạn không được phép truy cập phân hệ này.'));
			}
		
			$user_id = get_user_id();			
			$post = $this
				->Model->fetchRow("SELECT * FROM `calendars` 
					WHERE `created_by_id`='$user_id' 
						AND `type`='company' 
						AND `is_draft`='yes' LIMIT 1");
			if( $post ){
				$calendar_id = $post['ID'];
			}else{
				$this->Model->insert('calendars',array(
					type			=> 'company',
					is_draft		=> 'yes',
					created_by_id	=> $user_id
				));			
				$calendar_id = $this->Model->lastId();			
			}
			$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");
				
			$this->getOptions();	

			$this->set(array(
				post		=> $post,
				user		=> $user
			));					
					
			if( isPost() ){
				loadClass("ZData");
				$form = new ZData();
				$form->addField( $this->fields());
				$data = $this->checkData( $form->getData(), $form );
				if( !is_array( $data ) ){
					return $this->setJSON(array(
						message	=>	error($data)
					));
				}
				
				$data['is_draft'] = 'no';
				$data['date_created'] = mysql_date();
				$data['created_by_id'] = get_user_id();
				
				if( get('no_date_end','no') == 'yes' ){
					$data['repeat_date_end'] = NULL;
				}
				
				$this->Model->update('calendars',$data,"`ID`='$calendar_id'");
				
				$this->Model->delete('calendars_users',"`calendar_id`='$calendar_id'");				
				$users = (array)$_POST['users'];
				foreach( $users as $uid ){
					$id = (int)$uid;
					$user = $this->Model->fetchRow("SELECT `ID`,`phone` 
						FROM `users` WHERE `is_deleted`='no' AND `ID`='$id'");
					if( !$user ) continue;
						
					$this->Model->insert('calendars_users',array(
						calendar_id	=> $calendar_id,
						user_id		=> $id,
						is_guest	=> 'yes' 	
					));
					
					$this->Model->insert('notices',array(
						created_by_id	=> $user_id,
						user_id			=> $id,
						url				=> "#Calendar/Company/View?ID=$calendar_id",
						title			=> $data['title'],
						content			=> "Bạn có mặt trong một sự kiện mới",
						date			=> mysql_date()
					));

					//SMS
					if( get('sms_content','') !='' && is_cellphone($user['phone']) ){
						sendSMS(array(
							content			=>	get('sms_content'),
							user_id			=>	$user_id,
							address			=>	$user['phone'],
							date_created	=>	new Model_Expr('NOW()'),
							date_send		=>	new Model_Expr('NOW()'),
							mode			=>	'calendar',
							post_id			=>	$calendar_id	
						),$this->Model);
					}					
				}		

				//more
				$phones = (array)$_POST['sms_phone'];
				foreach( $phones as $number ){
					if( get('sms_content','') !='' && is_cellphone($number) ){
						sendSMS(array(
							content			=>	get('sms_content'),
							user_id			=>	$user_id,
							address			=>	$number,
							date_created	=>	new Model_Expr('NOW()'),
							date_send		=>	new Model_Expr('NOW()'),
							mode			=>	'calendar',
							post_id			=>	$calendar_id	
						),$this->Model);
					}
				}
				
				
				$this->setJSON(array(
					redirect => "#Calendar/Company/View?ID=$calendar_id"	
				));	
			}			
		}

		public function editAction(){
			$calendar_id = get('ID',0);
			$user_id = get_user_id();
			$post = $this
				->Model
				->fetchRow("SELECT * FROM `calendars` 
					WHERE 
						`ID`='$calendar_id' 
						AND `is_draft`='no'
						AND `type`='company'
						AND `created_by_id`='$user_id'");
			
			if( !$post ){
				return $this->setContent(error("Bản ghi không tồn tại hoặc đã bị xóa"));	
			}
			
			if( ( $post['created_by_id'] != $user_id ) && !$this->hasRole('add_company_calendar') ){
				return $this->setJSON(array(
					alert => 'Bạn không có quyền sửa sự kiện này.'			
				));
			}			
			
			$users = $this
				->Model->fetchAll("SELECT * 
					FROM `users` as `a` 
					LEFT JOIN `calendars_users` as `b`
						ON `b`.`user_id`=`a`.`ID` 
							AND `b`.`calendar_id`='$calendar_id'
					WHERE 
						`b`.`calendar_id`='$calendar_id'");
			
			$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='{$post['created_by_id']}'");
			
			$this->getOptions();
			$this->set(array(
				users	=> $users,
				post	=> $post,
				user	=> $user
			));
			
			if( isPost() ){
				loadClass("ZData");
				$form = new ZData();
				$form->addField( $this->fields());
				$data = $this->checkData( $form->getData(), $form );
				
				if( !is_array( $data ) ){
					$this->setJSON(array(
						message	=>	error($data)
					));				
				}

				if( get('no_date_end','no') == 'yes' ){
					$data['repeat_date_end'] = NULL;
				}
				
				$this->Model->update('calendars',$data,"`ID`='$calendar_id'");
				$this->Model->delete('calendars_users',"`calendar_id`='$calendar_id'");
				
				$users = (array)$_POST['users'];
				foreach( $users as $uid ){
					$id = mysql_escape_data($uid);
					$user = $this->Model->fetchRow("SELECT `ID`,`phone` FROM `users` WHERE `ID`='$id' AND `is_deleted`='no'");
					
					if(!$user) continue;
						
					$this->Model->insert('calendars_users',array(
						calendar_id	=> $calendar_id,
						user_id		=> $id,
						is_guest	=> 'yes' 	
					));
					
					$this->Model->insert('notices',array(
						created_by_id	=> $user_id,
						user_id			=> $id,
						date			=> mysql_date(),
						title			=> $data['title'],
						url				=> "#Calendar/Company/View?ID=$calendar_id",
						content			=> "Bạn có mặt trong một sự kiện mới được chỉnh sửa."
					));

					//SMS
					if( get('sms_content','') !='' && is_cellphone($user['phone']) ){
					
						sendSMS(array(
							content			=>	get('sms_content'),
							user_id			=>	$user_id,
							address			=>	$user['phone'],
							date_created	=>	new Model_Expr('NOW()'),
							date_send		=>	new Model_Expr('NOW()'),
							mode			=>	'calendar',
							post_id			=>	$calendar_id	
						),$this->Model);
					}
					
				}				
				
				$phones = (array)$_POST['sms_phone'];
				foreach( $phones as $number ){
					if( get('sms_content','') !='' && is_cellphone($number) ){
						sendSMS(array(
							content			=>	get('sms_content'),
							user_id			=>	$user_id,
							address			=>	$number,
							date_created	=>	new Model_Expr('NOW()'),
							date_send		=>	new Model_Expr('NOW()'),
							mode			=>	'calendar',
							post_id			=>	$calendar_id	
						),$this->Model);
					}
				}
				
				$this->setJSON(array(
					redirect => "#Calendar/Company/View?ID=$calendar_id"	
				));	
			}		
		}
		
		public function viewAction(){
			$calendar_id = get('ID',0);
			$user_id 	 = get_user_id();
			
			$post = $this
				->Model->fetchRow("SELECT 
						`a`.*,
						`u`.`username` as `updated_by_name`,
						`u`.`is_deleted` as `updated_is_deleted`
					FROM `calendars` as `a`
					LEFT JOIN `users` as `u`
						ON `u`.`ID`=`a`.`updated_by_id`
					WHERE 
						`a`.`is_draft`='no' 
						AND `type`='company' 
						AND `a`.`ID`='$calendar_id'");

			if( !$post ){
				return $this->setContent(error('Bản ghi không tồn tại hoặc đã bị xóa'));			
			}
			
			$guests = $this
				->Model->fetchAll("SELECT * 
					FROM `users` as `a` 
					LEFT JOIN `calendars_users` as `b`
						ON `b`.`user_id`=`a`.`ID` 
							AND `b`.`calendar_id`='$calendar_id'
					WHERE `b`.`calendar_id`='$calendar_id'");
					
			$this->set(array(
				post	=> $post,
				guests	=> $guests
			));
		}
		
		public function deleteAction(){
			$this->removeLayout();
			$calendar_id = get('ID',0);
			$user_id = get_user_id();
			
			$post = $this->Model->fetchRow("SELECT * FROM `calendars` 
				WHERE `ID`='$calendar_id' AND `type`='company'");

			if( !$post ){
				return $this->setJSON(array(
					alert => 'Bản ghi không tồn tại hoặc đã bị xóa'			
				));
			}
			
			if( ( $post['created_by_id'] != $user_id ) && !$this->hasRole('add_company_calendar') ){
				return $this->setJSON(array(
					alert => 'Bạn không có quyền xóa Sự kiện này.'			
				));
			}
						
			$this->Model->delete('calendars',"`ID`='$calendar_id'");
			$this->Model->delete('calendars_users',"`calendar_id`='$calendar_id'");
			
			return $this->setJSON(array(
				redirect => get('redirect_url','#Calendar/Company')
			));		
		}

	}
 ?>